package com.icloud.common.web.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.icloud.common.core.api.ResultCode;
import com.icloud.common.core.constant.AuthConstant;
import com.icloud.common.web.domain.UserDto;
import com.icloud.common.web.exception.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@Component
public class AuthUtil {
    private HttpServletRequest request;

    @Autowired
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * 从请求头中获取用户信息(由网关全局过滤器中设置用户信息)
     */
    private UserDto getUserFromHeader() {
        String userStr = request.getHeader(AuthConstant.USER_TOKEN_HEADER);
        if(StrUtil.isBlank(userStr)){
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }
        return JSONUtil.toBean(userStr, UserDto.class);
    }

    /**
     * 获取用户ID
     */
    public Long getUserId() {
        UserDto userDto = getUserFromHeader();
        return userDto.getId();
    }

    /**
     * 获取username
     */
    public String getUsername() {
        UserDto userDto = getUserFromHeader();
        return userDto.getUsername();
    }

    /**
     * 获取昵称
     */
    public String getNickname() {
        UserDto userDto = getUserFromHeader();
        //由于header中文乱码。设置采用utf-8编码，此处对应解码
        return URLUtil.decode(userDto.getNickname(), StandardCharsets.UTF_8);
    }

    public String getAuthHashKey(){
        UserDto userDto = getUserFromHeader();
        return userDto.getClientId()+"_"+userDto.getId();
    }

    /**
     * 是否前端客户
     */
    public boolean isCustomer(){
        UserDto userDto = getUserFromHeader();
        return AuthConstant.APP_CLIENT_ID.equals(userDto.getClientId());
    }
}
